import axios from 'axios'
import JSONBig from 'json-bigint'
import { resResolve, resReject, reqResolve, reqReject } from './interceptor'
import config from '../config'

export function createAxios( options = {}) {
  const defaultOptions = {
    baseURL: config.baseURL,
    timeout: 10000,
    headers: { 'content-type': 'application/json;charset=UTF-8' },
    transformResponse: [
      // eslint-disable-next-line func-names
      function ( data ) {
        try {
          return JSONBig.parse( data )
        } catch ( err ) {
          return data
        }
      }
    ]
  }

  const service = axios.create({
    ...defaultOptions,
    ...options
  })

  service.interceptors.request.use( reqResolve, reqReject )
  service.interceptors.response.use( resResolve( service ), resReject )
  return service
}

export const getRequest = createAxios({ method: 'get' })
export const postRequest = createAxios({ method: 'post' })
export const putRequest = createAxios({ method: 'put' })
export const deleteRequest = createAxios({ method: 'delete' })
